package command
{
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import event.TriviaEvent;
	
	import flash.net.URLRequestMethod;
	
	import model.ApplicationModel;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import vo.Answer;
	import vo.Question;
	
	public class QuestionsManagerCommand extends BaseCommand
	{
		
		private var _model:ApplicationModel=ApplicationModel.instance;
		private var xEvent:TriviaEvent; 

		public override function doExecute(event:CairngormEvent):void
		{
			xEvent = event as TriviaEvent;
			// Test parametros 
			var params:Object = new Object();
			params.levelID = _model.level;
			var httpService:HTTPService = new HTTPService();
			httpService.url= _model.URL_QUESTIONS;
			httpService.useProxy = false;
			httpService.addEventListener(ResultEvent.RESULT,onResult);
          	httpService.addEventListener(FaultEvent.FAULT, onFault);
          	httpService.method = URLRequestMethod.POST;
          	httpService.send(params);	
          	
		}

		public function onResult(data:Object):void
		{
			
			var resultObj:Object = data.result;
			var i:int=0;
			_model.questions= new ArrayCollection();
			
			while (resultObj.data.questions.question.length > i)
			{
				var question:Question = new Question();
				question.statement =  resultObj.data.questions.question[i].statement;
				question.id =  resultObj.data.questions.question[i].id;
				
				// For new version
				//question.correctAnswer = resultObj.questions.question[i].correctAnswer;
				//question.level = resultObj.questions.question[i].level;
				// question.score = resultObj.questions.question[i].score;
				question.helpmessage = resultObj.data.questions.question[i].helpMessage;

				// Itero sobre las respuestas
				var j:int=0;
				while (resultObj.data.questions.question[i].answers.answer.length > j)
				{
					var answer:Answer = new Answer();
					answer.id = resultObj.data.questions.question[i].answers.answer[j].id;
					answer.statement = resultObj.data.questions.question[i].answers.answer[j];
					if (new Boolean(resultObj.data.questions.question[i].answers.answer[j].status))
					{
						question.correctAnswer = answer.id;
					}
					question.lsAnswer.addItem(answer);
					j++;
				}
				
				_model.questions.addItem(question);
				i++;
			}
			_model.currentIndex=-1;
			
			if (xEvent.endFunction!=null)
				xEvent.endFunction();

		}	
		
		
		public function onFault(data:Object):void
		{
			Alert.show("Fail","Fail");
		}

	}
}